import { useUserStore } from "@/store/modules/user";
import { postSalt, postLogin } from "@/api/path/user";
import { openNotify } from "@/hooks/web/useNotify.hook";
import { NotifyTypeEnum } from "@/enums/notify.enum";
import { encryptPassword } from "./encrypt";

interface LoginInfo {
    email: string;
    password: string;
}

/**
 * 登录
 * @param info 登录信息
 */
export const login = async (info: LoginInfo): Promise<boolean> => {
    const userStore = useUserStore();
    const saltRes = await postSalt(info.email);
    if (!saltRes) return false;
    const safePassword = await encryptPassword(info.password, saltRes.slat);
    const loginRes = await postLogin(saltRes.id, safePassword);
    if (!loginRes?.success) {
        openNotify({
            title: "登录失败",
            message: "用户名或密码错误，请重试",
            type: NotifyTypeEnum.ERROR
        });
        return false;
    }
    userStore.loginAction({ ...loginRes });
    return true;
};

/**
 * 退出登录
 */
export const logout = () => {
    const userStore = useUserStore();
    userStore.logoutAction();
};
